package com.sugar.factory;


import com.sugar.properties.ThreadPoolProperties;

import java.util.concurrent.*;

public class ThreadPoolFactory {

    public static ExecutorService build(ThreadPoolProperties props) {
        int cpu = Runtime.getRuntime().availableProcessors();
        int core = props.getCorePoolSize();
        int max = props.getMaxPoolSize();

        switch (props.getProfile()) {
            case CPU_INTENSIVE:
                core = (core > 0) ? core : cpu + 1;
                max = (max > 0) ? max : cpu * 2;
                break;
            case IO_INTENSIVE:
                core = (core > 0) ? core : cpu * 2;
                max = (max > 0) ? max : cpu * 4;
                break;
            case MIXED:
            default:
                core = (core > 0) ? core : cpu * 2;
                max = (max > 0) ? max : cpu * 3;
                break;
        }


        return new ThreadPoolExecutor(
                core,
                max,
                props.getKeepAliveSeconds(),
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(props.getQueueCapacity()),
                new ThreadFactory() {
                    private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
                    private int count = 0;

                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = defaultFactory.newThread(r);
                        thread.setName(props.getThreadNamePrefix() + count++);
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
}

